package com.example.search;

import java.util.LinkedList;

public class SeparateChainingHashTable {
    private static final int DEFAULT_CAPACITY = 13; // 默认容量，最好设为质数
    private LinkedList<Integer>[] buckets; // 每个桶是一个链表

    public SeparateChainingHashTable() {
        buckets = new LinkedList[DEFAULT_CAPACITY];
        for (int i = 0; i < DEFAULT_CAPACITY; i++) {
            buckets[i] = new LinkedList<>();
        }
    }

    // 哈希函数
    private int hash(int key) {
        return key % buckets.length;
    }

    // 插入操作
    public void insert(int key) {
        int index = hash(key);
        buckets[index].add(key);
    }

    // 查找操作
    public boolean search(int key) {
        int index = hash(key);
        return buckets[index].contains(key);
    }

    // 删除操作
    public void delete(int key) {
        int index = hash(key);
        buckets[index].remove(Integer.valueOf(key));
    }

    public static void main(String[] args) {
        SeparateChainingHashTable hashTable = new SeparateChainingHashTable();
        hashTable.insert(10);
        hashTable.insert(20);
        hashTable.insert(30);
        hashTable.insert(40);

        System.out.println("Search for 20: " + hashTable.search(20)); // 输出 true
        System.out.println("Search for 50: " + hashTable.search(50)); // 输出 false

        hashTable.delete(20);
        System.out.println("After deleting 20, search for 20: " + hashTable.search(20)); // 输出 false
    }
}